# -*- coding: utf-8 -*-
# @Time    : 2020/6/30 20:17
# @Author  : lerry-lee
# @Version : 1.0
# @Description: 翻译


# 百度通用翻译API,不包含词典、tts语音合成等资源，如有相关需求请联系translate_api@baidu.com
# coding=utf-8

import http.client
import hashlib
import urllib
import random
import json


import logging

log=logging.getLogger("mylog")


def main(q_str):
    appid = '20200630000509939'  # 填写你的appid
    secretKey = 'iXxSrJWkG3jnPpWeZWut'  # 填写你的密钥

    httpClient = None
    myurl = '/api/trans/vip/translate'

    fromLang = 'zh'  # 原文语种
    toLang = 'en'  # 译文语种
    salt = random.randint(32768, 65536)

    q = q_str
    sign = appid + q + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
        q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
        salt) + '&sign=' + sign

    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)

        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)

        log.info(result)

        res = result["trans_result"][0]

        return res
        # save_trans_res(result,file_name)

    except Exception as e:
        log.error(e)
    finally:
        if httpClient:
            httpClient.close()


import pandas as pd


def save_trans_res(result, file_name):
    raw_list = []
    trans_list = []
    for dic in result["trans_result"]:
        raw_list.append(dic["src"])
        trans_list.append(dic["dst"])
    df = pd.DataFrame()
    df[0] = raw_list
    df[1] = trans_list
    df.to_csv("en_trans/en_{}".format(file_name), index=False, header=None, sep="\t")
